package cn.edu.sdjzu.mocige_server.service.jwt;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;

@Slf4j
@Service // @Service注解表示该类被Spring管理
public class JwtService {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    public String generateToken(String username) {
        // 生成安全的签名密钥
        byte[] keyBytes = Decoders.BASE64.decode(secret);
        Key signingKey = Keys.hmacShaKeyFor(keyBytes);

        // 生成JWT令牌
        return "Bearer " + Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(signingKey, SignatureAlgorithm.HS256)
                .compact();
    }

    // 从令牌中获取用户名
// 从令牌中获取用户名
    public String getUsernameFromToken(String token) {
        byte[] keyBytes = Decoders.BASE64.decode(secret);
        Key signingKey = Keys.hmacShaKeyFor(keyBytes);

        return Jwts.parserBuilder()
                .setSigningKey(signingKey)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
    // 验证令牌是否有效
// 验证令牌是否有效
    public boolean validateToken(String token) {
        try {
            byte[] keyBytes = Decoders.BASE64.decode(secret);
            Key signingKey = Keys.hmacShaKeyFor(keyBytes);
            Date expirationDate = Jwts.parserBuilder()
                    .setSigningKey(signingKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration();
            return true;
        } catch (ExpiredJwtException e) {
            log.error("JwtAuthenticationFilter: {}", e.getMessage());
            return false;
        } catch (Exception e) {
            log.error("过期: {}", e.getMessage());
            return false;
        }
    }

}
